<?php
/**
 * 描述
 * Created by Paco
 * Date: 2019/1/29 Time: 18:03
 */

namespace App\Repositories\Shop;


use App\Models\Product\Img;
use App\Models\Product\ProAttribue;
use App\Models\Product\Product;
use App\Models\Product\ProModel;
use App\Models\Product\Sku;
use App\Repositories\Repository;
use Illuminate\Support\Facades\DB;

class ProductRepository extends Repository
{

    public function index($params)
    {
        $user = $this->getUser();
        $products = Product::query()->orderBy('created_at', 'desc')
            ->where('shop_id', $user->shop_id)
            ->where('is_del', 0)
            ->when(!empty($params['cat_id']), function ($query) use ($params) {
                $query->where('cat_id', $params['cat_id']);
            })->when(!empty($params['product_name']), function ($query) use ($params) {
                $query->where('product_name', 'like', '%' . $params['product_name'] . '%');
            })->paginate($this->page_size, ['*'], 'page', $this->page);
        return $this->respondWith($products);
    }


    public function show($pro_id)
    {
        $user = $this->getUser();
        $product = Product::query()->where('shop_id', $user->shop_id)
            ->where('product_id', $pro_id)
            ->where('is_del', 0)
            ->first();
        if (!$product) {
            $this->throwRespondError(10109);
        }

        $imgs = Img::query()->where('product_id', $pro_id)->get();
        $attrs = ProAttribue::query()->where('product_id', $pro_id)->
        orderBy('pro_attr_id', 'asc')->get();
        $skus = Sku::query()->where('product_id', $pro_id)
            ->where('status', 0)
            ->get();
        $specs = [];
        $temp_attrs = [];
        foreach ($attrs as $attr) {
            if (!$attr->is_spec) {
                $temp_attrs[] = $attr;
            } else {
                $specs[] = $attr;
            }
        }
        $data = [
            'product' => $product,
            'imgs' => $imgs,
            'attrs' => $temp_attrs,
            'specs' => $specs,
            'skus' => $skus
        ];
        return $this->respondWith($data);
    }


    public function getModel($model_id)
    {
        $model = ProModel::query()->where('model_id', $model_id)->where('status', 0)->first();
        if (!$model) {
            $this->throwRespondError(10109);
        }
        $model->attribue = json_decode($model->attribue);
        $model->extend = json_decode($model->extend);
        return $this->respondWith($model);
    }

    public function store($data)
    {
        $user = $this->getUser();
        DB::beginTransaction();
        try {
            $data['cover_img'] = $data['imgs'][0];
            $data['shop_id'] = $user->shop_id;
            //添加产品
            $product = Product::query()->create($data);
            //添加图片
            $imgs = $this->addImg($product->product_id, $data['imgs']);
            if (!$imgs) {
                DB::rollBack();
                $this->throwRespondError(10110);
            }

            //添加产品属性
            $attr = $this->addAttribue($product->product_id, $data['attrs'], $data['spec']);
            if (!$attr) {
                DB::rollBack();
                $this->throwRespondError(10110);
            }

            //添加sku
            $sku = $this->addSku($product->product_id, $data['skus']);
            if (!$sku) {
                DB::rollBack();
                $this->throwRespondError(10110);
            }
            DB::commit();
            return $this->respondSuccess();
        } catch (\Exception $e) {
            DB::rollBack();
            $this->throwRespondWithMessage($e->getMessage());
            $this->throwRespondError(10110);
        }
    }


    public function savePro($data)
    {
        $user = $this->getUser();
        $product = Product::query()->where('shop_id', $user->shop_id)->find($data['product_id']);

        if (!$product) {
            $this->throwRespondError(10109);
        }

        DB::beginTransaction();
        try {

            //前端标识是否有修改图片，如果有，则删除原有的图片，再添加新图片
            if ($data['edit_img']) {
                //删除图片
                $this->delImg($data['product_id']);
                //添加图片
                $this->addImg($product->product_id, $data['imgs']);
            }

            ProAttribue::query()->where('product_id', $product->product_id)->delete();
            $this->addAttribue($product->product_id, $data['attrs'], $data['spec']);


            $sku = $this->addSku($product->product_id, $data['skus']);
            if (!$sku) {
                DB::rollBack();
                $this->throwRespondError(10110);
            }
            if (isset($data['status'])) {
                unset($data['status']);
            }
            if (isset($data['checked'])) {
                unset($data['checked']);
            }
            $product->fill($data)->save();
            DB::commit();
            return $this->respondSuccess();

        } catch (\Exception $e) {
            DB::rollBack();
            $this->throwRespondWithMessage($e->getMessage());
            $this->throwRespondError(10110);
        }
    }


    public function delProduct($pro_ids)
    {
        if (!is_array($pro_ids)) {
            $pro_ids = explode(',', $pro_ids);
        }
        $user = $this->getUser();
        try {
            Product::query()->where('shop_id', $user->shop_id)
                ->whereIn('product_id', $pro_ids)
                ->update(['is_del' => 1]);
            return $this->respondSuccess();
        } catch (\Exception $e) {
            return $this->respondError(10108);
        }
    }


    public function shelves($pro_ids,$shelves)
    {
        if (!is_array($pro_ids)) {
            $pro_ids = explode(',', $pro_ids);
        }
        $user = $this->getUser();
        try {
            Product::query()->where('shop_id', $user->shop_id)
                ->whereIn('product_id', $pro_ids)
                ->update(['shelves' => $shelves]);
            return $this->respondSuccess();
        } catch (\Exception $e) {
            return $this->respondError(10108);
        }
    }


    public function delSku($sku_id)
    {
        try {
            Sku::query()->where('sku_id', $sku_id)->delete();
            return $this->respondSuccess();
        } catch (\Exception $e) {
            return $this->respondError(10107);
        }
    }


    private function addImg($pro_id, $imgs)
    {
        $rs = true;
        if (count($imgs)) {
            $data = [];
            $date = date('Y-m-d H:i:s');
            foreach ($imgs as $k => $img) {
                $data[] = [
                    'product_id' => $pro_id,
                    'url' => $img,
                    'created_at' => $date,
                    'updated_at' => $date,

                ];
            }
            $rs = Img::query()->insert($data);
        }
        return $rs;
    }

    private function delImg($pro_id)
    {
        return Img::query()->where('product_id', $pro_id)->delete();
    }

    private function addAttribue($pro_id, $attrs, $specs)
    {
        $rs = true;
        if (count($attrs)) {
            $data = [];
            foreach ($attrs as $k => $attr) {
                $attr_value_id = $attr['attr_value_id'];
                if (is_array($attr['attr_value_id'])) {
                    $attr_value_id = implode(',', $attr['attr_value_id']);
                }
                $attr_value_name = $attr['attr_value_name'];
                if (is_array($attr['attr_value_name'])) {
                    $attr_value_name = implode(',', $attr['attr_value_name']);
                }

                $data[] = [
                    'attr_name_id' => $attr['attr_name_id'],
                    'attr_value_name' => $attr_value_name,
                    'attr_value_id' => $attr_value_id,
                    'attr_name_name' => $attr['attr_name_name'],
                    'is_spec' => $attr['is_spec'] ?? 0,
                    'group_number' => $attr['group_number'] ?? '',
                    'group_name' => $attr['group_name'] ?? '',
                    'img' => $attr['img'] ?? '',
                    'product_id' => $pro_id
                ];
            }

            foreach ($specs as $k => $spec) {
                $attr_value_id = $spec['attr_value_id'];
                if (is_array($spec['attr_value_id'])) {
                    $attr_value_id = implode(',', $spec['attr_value_id']);
                }
                $attr_value_name = $spec['attr_value_name'];
                if (is_array($spec['attr_value_name'])) {
                    $attr_value_name = implode(',', $spec['attr_value_name']);
                }
                $data[] = [
                    'attr_name_id' => $spec['attr_name_id'],
                    'attr_value_name' => $attr_value_name,
                    'attr_value_id' => $attr_value_id,
                    'attr_name_name' => $spec['attr_name_name'],
                    'is_spec' => 1,
                    'group_number' => '',
                    'group_name' => '',
                    'img' => '',
                    'product_id' => $pro_id
                ];
            }

            $rs = ProAttribue::query()->insert($data);
        }
        return $rs;
    }

    private function updateSku($sku)
    {
        if (count($sku)) {
            Sku::query()->where('sku_id', $sku['sku_id'])->update($sku);
        }
    }

    private function addSku($pro_id, $skus)
    {
        $rs = true;
        if (count($skus)) {

            $data = [];
            $date = date('Y-m-d H:i:s');
            foreach ($skus as $k => $sku) {
                if (empty($sku['sku_price']) || empty($sku['spec_ids'])) {
                    continue;
                }


                $spec_ids_json = json_encode($sku['spec_ids']);
                $spec_ids = [];
                foreach ($sku['spec_ids'] as $spec_id) {
                    $spec_ids[] = $spec_id;
                }
                sort($spec_ids);
                $spec_ids = implode('-', $spec_ids);

                //更新原有的sku
                if (isset($sku['sku_id'])) {
                    $temp = [
                        'sku_id' => $sku['sku_id'],
                        'product_id' => $pro_id,
                        'sku_price' => $sku['sku_price'],
                        'status' => $sku['status'],
                        'spec_ids' => $spec_ids,
                        'spec_ids_json' => $spec_ids_json,
                        'spec' => $sku['spec'],
                        'stock' => $sku['stock'],
                        'product_number' => $sku['product_number'],
                        'sku_weight' => $sku['sku_weight'],
                        'sku_bulk' => $sku['sku_bulk'],
                    ];
                    $this->updateSku($temp);
                    continue;
                }
                $spec = json_encode($sku['spec']);
                $data[] = [
                    'product_id' => $pro_id,
                    'sku_price' => $sku['sku_price'],
                    'status' => $sku['status'],
                    'spec_ids' => $spec_ids,
                    'spec_ids_json' => $spec_ids_json,
                    'spec' => $spec,
                    'stock' => $sku['stock'],
                    'product_number' => $sku['product_number'],
                    'created_at' => $date,
                    'updated_at' => $date,
                    'sku_weight' => $sku['sku_weight'],
                    'sku_bulk' => $sku['sku_bulk'],
                ];


            }
            $rs = Sku::query()->insert($data);
        }
        return $rs;
    }

}